package com.itheima.bigeventt.controller;

import com.itheima.bigeventt.pojo.Category;
import com.itheima.bigeventt.pojo.Result;
import com.itheima.bigeventt.service.CategoryService;
import com.itheima.bigeventt.service.UserService;
import com.itheima.bigeventt.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private UserService userService;

    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer id = userService.findByUserName((String) map.get("username")).getId();
        category.setCreateUser(id);
        categoryService.save(category);
        return Result.success("添加成功");
    }

    @GetMapping
    public Result<List<Category>> list() {
        List<Category> list = categoryService.list();
        return Result.success(list);
    }

    @GetMapping("/detail")
    public Result<Category> detail(Integer id) {
        Category category = categoryService.getById(id);
        return Result.success(category);
    }

    @PutMapping
    public Result update(@RequestBody @Validated(Category.Update.class) Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryService.updateById(category);
        return Result.success("更新成功");

    }

    @DeleteMapping
    public Result delete( Integer id) {
        categoryService.removeById(id);
        return Result.success("删除成功");
    }
}
